<?php
namespace app\know\validate;

use app\know\model\PaperModel;
use app\know\validate\KnowBaseValidate;

class PaperValidate extends KnowBaseValidate
{
    protected $rule = [
        'material_uuid' => 'require|length:32',
        'chapter_uuid' => 'require|length:32',
		'name' => 'require|checkName',
        'type' => 'require|checkType',
        'uuid' => 'require',
    ];

    protected $message = [
        'material_uuid.require' => '教材ID为必填项',
        'material_uuid.length' => '教材ID不能为空',	
        'chapter_uuid.require' => '章节ID为必填项',
        'chapter_uuid.length' => '章节ID不能为空',	
        'name.require' => '试卷为必填项',	
        'type.require' => '类型为必填项',
        'type.checkType' => '类型不合法',
        'uuid.require' => 'uuid不能为空',
    ];

    protected $scene = [
        'type'  => ['type'],
        'addZJLX'  => ['material_uuid', 'chapter_uuid', 'name'],
        'editZJLX' => ['chapter_uuid', 'name', 'uuid'],
        'delete' => ['uuid'],
    ];

    protected function checkType($value, $rule, $data)
    {
        $arr = ['ZJLX'];
        return in_array($data['name'], $arr) === false;
    }

    protected function checkZJLX($value, $rule, $data)
    {
        $w = ['is_delete' => 0, 'material_uuid' => $data['material_uuid'], 'chapter_uuid' => $data['chapter_uuid']];
        $item = PaperModel::where($w)->find();

        if (empty($item)) 
        {
            return true;
        } 
        else 
        {
            return "---章节习题已经存在---";
        }
    }

    protected function checkName($value, $rule, $data)
    {
        if ($this->currentScene === 'addZJLX') 
        {
            return $this->checkZJLX($value, $rule, $data);
        }
        else if ($this->currentScene === 'editZJLX') 
        {
            return true;
        }

        $w = ['is_delete' => 0, 'type' => $data['type'], 'name' => $data['name']];
        $item = PaperModel::where($w)->find();

        if (empty($item)) 
        {
            return true;
        } 
        else 
        {
            return $data['name'] . "---已经存在---";
        }
    }
    
}